<template>
  <div class="page">
    <div class="top">
      <div class="header">
        <a href="/">
          <img src="/logo.png" class="logo" alt="logo" />
          <span class="title">chaos saas</span>
        </a>
      </div>
    </div>

    <div class="main">
      <a-form
        id="formLogin"
        class="user-layout-login"
        ref="formLogin"
        :model="formState"
        @finish="handleSubmit"
      >
        <a-alert
          v-if="isLoginError"
          type="error"
          showIcon
          style="margin-bottom: 24px"
          :message="message"
        />
        <a-form-item name="username" :rules="usernameRules">
          <a-input
            size="large"
            type="text"
            placeholder="请输入用户名"
            v-model:value="formState.username"
          >
            <template #prefix>
              <a-icon type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item name="password" :rules="passwordRules">
          <a-input-password
            size="large"
            placeholder="请输入密码"
            v-model:value="formState.password"
          >
            <template #prefix>
              <a-icon type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
            </template>
          </a-input-password>
        </a-form-item>
        <a-form-item style="margin-top: 24px">
          <a-button
            size="large"
            type="primary"
            htmlType="submit"
            class="login-button"
            :loading="loginBtn"
            :disabled="loginBtn"
          >
            登录
          </a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { message, notification } from 'ant-design-vue';
import { get, getByData, getData, list, login } from '@/services';
import { useTenantStore } from '@/stores/global';
import md5 from 'js-md5';

const router = useRouter();
const formLogin = ref(null);
const isLoginError = ref(false);
const loginBtn = ref(false);

const message = ref('');

const formState = reactive({
  username: '',
  password: '',
});

const usernameRules = [{ required: true, message: '用户名必填', trigger: 'change' }];

const passwordRules = [{ required: true, message: '密码必填', trigger: 'blur' }];

const clientDetails = ref({});
const authorizedGrantTypes = 'admin_username';
const tenantStore = useTenantStore();

onMounted(async () => {
  const clientDetailsData = await getByData('/api/auth/oauthClientDetails/saas', {
    tenantId: 0,
    authorizedGrantTypes,
  });
  clientDetails.value = clientDetailsData.data;
});

const dealInfo = async () => {
  const res = await getData('/api/elog/tenant/checkServiceValidity');
  if (res) {
    message.warn('系统服务有效期有足1个月，请及时续约');
  }
};

const handleSubmit = () => {
  loginBtn.value = true;

  formLogin.value
    .validateFields()
    .then(async values => {
      const loginParams = { ...values };
      const username = loginParams.username;
      const password = loginParams.password;
      const encryptedPassword = md5(password);

      const res = await login({
        username,
        password: encryptedPassword,
        client_id: clientDetails.value.clientId,
        client_secret: clientDetails.value.clientSecret,
        grant_type: authorizedGrantTypes,
      });

      const { success, msg, data } = res;
      if (success) {
        const { access_token, username, tenantId } = data;

        localStorage.setItem('access_token', access_token);
        localStorage.setItem('username', username);

        tenantStore.setTenantId(tenantId);
        const tenantData = await get('/api/auth/tTenant', tenantId);
        const { companyFullName, enterpriseCode } = tenantData.data;
        await localStorage.setItem('enterprise_code', enterpriseCode);
        await localStorage.setItem('enterprise_name', companyFullName);

        await router.push({ path: '/' });
        // 延迟 1 秒显示欢迎信息
        setTimeout(() => {
          notification.success({
            message: '欢迎',
            description: `欢迎回来`,
          });

          dealInfo();
        }, 1000);
      } else {
        isLoginError.value = true;
        loginBtn.value = false;
        message.value = msg;
      }
    })
    .catch(err => {
      setTimeout(() => {
        loginBtn.value = false;
      }, 600);
    });
};
</script>

<style lang="less" scoped>
.page {
  height: 100vh;
  background-color: #f0f2f5;
  background-image: url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr');

  .top {
    padding: 132px 0 24px;

    text-align: center;

    .header {
      height: 44px;
      line-height: 44px;

      .badge {
        position: absolute;
        display: inline-block;
        line-height: 1;
        vertical-align: middle;
        margin-left: -12px;
        margin-top: -10px;
        opacity: 0.8;
      }

      .logo {
        height: 44px;
        vertical-align: top;
        margin-right: 16px;
        border-style: none;
      }

      .title {
        font-size: 33px;
        color: rgba(0, 0, 0, 0.85);
        font-family: Avenir, 'Helvetica Neue', Arial, Helvetica, sans-serif;
        font-weight: 600;
        position: relative;
        top: 2px;
      }
    }

    .desc {
      font-size: 14px;
      color: rgba(0, 0, 0, 0.45);
      margin-top: 12px;
      margin-bottom: 40px;
    }
  }

  .main {
    display: flex;
    justify-content: center;
    align-items: center;

    .user-layout-login {
      width: 368px;
      padding: 32px 40px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

      .ant-form-item {
        margin-bottom: 24px;
      }

      .ant-alert {
        margin-bottom: 24px;
      }

      .ant-input-affix-wrapper {
        &.ant-input-affix-wrapper-lg {
          height: 40px;
        }
      }

      .login-button {
        width: 100%;
        height: 40px;
        font-size: 16px;
      }
    }
  }
}
</style>
